﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
using MvcApplication2.DAL;
using PagedList;

namespace MvcApplication2.Controllers
{
    public class BuildItemController : Controller
    {
        private ReleaseAutomationContext db = new ReleaseAutomationContext();

        //
        // GET: /BuildItem/

        //public ActionResult Index()
        //{
        //    return View(db.BuildItems.ToList());
        //}

        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
        
            {
                ViewBag.CurrentSort = sortOrder;
                ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Name_desc" : "";
                ViewBag.DateSortParm = sortOrder == "Date" ? "Date_desc" : "Date";

                if (searchString != null)
                {
                    page = 1;
                }
                else
                {
                    searchString = currentFilter;
                }

                ViewBag.CurrentFilter = searchString;


                var buildItems = from s in db.BuildItems
                    select s;

                if (!String.IsNullOrEmpty(searchString))
                {
                    buildItems = buildItems.Where(s => s.HumanReadableAppName.ToUpper().Contains(searchString.ToUpper())
                                                       || s.PackageName.ToUpper().Contains(searchString.ToUpper()));
                }


                switch (sortOrder)
                {
                    case "Name_desc":
                        buildItems = buildItems.OrderByDescending(s => s.HumanReadableAppName);
                        break;
                    case "Date":
                        buildItems = buildItems.OrderBy(s => s.AppMapPackageId);
                        break;
                    case "Date_desc":
                        buildItems = buildItems.OrderByDescending(s => s.AppMapPackageId);
                        break;
                    default:
                        buildItems = buildItems.OrderBy(s => s.HumanReadableAppName);
                        break;
                }

                int pageSize = 3;
                int pageNumber = (page ?? 1);
                return View(buildItems.ToPagedList(pageNumber, pageSize));

                //return View(buildItems.ToList());
            }
        }

        //
        // GET: /BuildItem/Details/5

        public ActionResult Details(int id = 0)
        {
            BuildItem builditem = db.BuildItems.Find(id);
            if (builditem == null)
            {
                return HttpNotFound();
            }
            return View(builditem);
        }

        //
        // GET: /BuildItem/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /BuildItem/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(
            [Bind(Include = "AppMapPackageId, PackageName, HumanReadableAppName, CommandLine, WorkingDir, CreationDate")]
            BuildItem builditem)

        {
            try
            {


                if (ModelState.IsValid)
                {
                    db.BuildItems.Add(builditem);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
                //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");  
            }
            return View(builditem);
        }

        //
        // GET: /BuildItem/Edit/5

        public ActionResult Edit(int id = 0)
        {
            BuildItem builditem = db.BuildItems.Find(id);
            if (builditem == null)
            {
                return HttpNotFound();
            }
            return View(builditem);
        }

        //
        // POST: /BuildItem/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "AppMapPackageId, PackageName, HumanReadableAppName, CommandLine, WorkingDir, CreationDate")]
            BuildItem builditem)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(builditem).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException)
            {
                //Log the error (uncomment dex variable name after DataException and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }

            return View(builditem);
        }

        //
        // GET: /BuildItem/Delete/5

        public ActionResult Delete(bool? saveChangesError = false, int id = 0)
        {
            if (saveChangesError.GetValueOrDefault())
            {
                ViewBag.ErrorMessage = "Delete failed. Try again, and if the problem persists see your system administrator.";
            }
            BuildItem builditem = db.BuildItems.Find(id);
            if (builditem == null)
            {
                return HttpNotFound();
            }

            return View(builditem);
        }

        //
        // POST: /BuildItem/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id)
        {
            try
            {
                //BuildItem buildItem = db.BuildItems.Find(id);
                //db.BuildItems.Remove(buildItem);
                BuildItem buildItemToDelete = new BuildItem() { BuildItemId = id };
                db.Entry(buildItemToDelete).State = EntityState.Deleted;
                db.SaveChanges();
            }
            catch (DataException/* dex */)
            {
                // uncomment dex and log error. 
                return RedirectToAction("Delete", new { id = id, saveChangesError = true });
            }
            return RedirectToAction("Index");

        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}